package 链表.旋转链表;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/5/9 16:29
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        ListNode head = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5)))));
        System.out.println(rotateRight(head, 2).val);
    }

    public static ListNode rotateRight(ListNode head, int k) {
        ListNode root = new ListNode(-1,head);
        ListNode p = head,r = head;
        int total = 0;
        if (head == null || head.next == null) {
            return head;
        }
        //将指针r指向链表的尾部
        while (p != null) {
            total++;
            p = p.next;
            if (r.next != null) {
                r = r.next;
            }
        }
        if (k >= total) {
            k = k % total;
        }
        // k为0时表示无需移动
        if (k == 0) {
            return root.next;
        }
        int target = total - k;
        ListNode s = root.next;
        int tmp = 1;
        while (target != tmp) {
            tmp++;
            s = s.next;
            if (target == tmp) {
                ListNode res = s.next;
                s.next = null;
                r.next = root.next;
                return res;
            }
        }
        return head;
    }
}
